package
{
      import com.pblabs.engine.PBE;
      import com.pblabs.engine.components.TickedComponent;
      import com.pblabs.engine.core.InputKey;
      import com.pblabs.engine.entity.PropertyReference;

      import flash.events.Event;
      import flash.geom.Point;

      public class KeyboardControllerComponent extends TickedComponent
      {
            // Defines the speed that this Component will move a game
            // element by
            protected static const MOVEMENT_SPEED:Number = 50;
            // A reference to the position property of another Component
            public var positionReference:PropertyReference;

            public function KeyboardControllerComponent()
            {

            }

            // The onTick() function is called once per frame
            public override function onTick(tickRate:Number):void
            {
                  // Get the position of the external Component
                  var position:Point =
                        owner.getProperty(positionReference);

                  // Check to see if any of the arrow keys are pressed,
                  // and if so, modify the position variable accordingly
                  if (PBE.isKeyDown(InputKey.UP))
                        position.y -= MOVEMENT_SPEED * tickRate;
                  else if (PBE.isKeyDown(InputKey.DOWN))
                        position.y += MOVEMENT_SPEED * tickRate;
                  if (PBE.isKeyDown(InputKey.LEFT))
                        position.x -= MOVEMENT_SPEED * tickRate;
                  else if (PBE.isKeyDown(InputKey.RIGHT))
                        position.x += MOVEMENT_SPEED * tickRate;

                  // Set the  position of the external Component
                  owner.setProperty(positionReference, position);

                  // Notify other Components that they should "Go"
                  var gKeyCode:int = InputKey.G.keyCode;
                  if (PBE.inputManager.keyJustReleased(gKeyCode))
                  {
                        owner.eventDispatcher.dispatchEvent(
                              new Event("Go"));
                  }

                  // Notify other Components that they should "Stop"
                  var sKeyCode:int = InputKey.S.keyCode;
                  if (PBE.inputManager.keyJustReleased(sKeyCode))
                  {
                        owner.eventDispatcher.dispatchEvent(
                              new Event("Stop"));
                  }
            }
      }
}